package com.tanran.taolijin.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;


import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Enzo Cotter on 2019/10/22.
 */
@Component
@Slf4j
public class TaobaoApi {
    /**
     * 将淘宝密令转换成连接
     * @param ml
     * @return
     */
    public static String parseMl(String ml){
        String result="";
        try {
            //OkHttpUtils.get()
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("passwordContent",ml);
            String data=jsonObject.toJSONString();
            String url="https://api.m.taobao.com/gw/mtop.taobao.sharepassword.querypassword/1.0/";
            HashMap<String, String> paramMap = new HashMap<>();
            paramMap.put("data", URLEncoder.encode(data,"UTF-8"));
            result=OkHttpUtils.postForm(url, createHeader(), paramMap, String.class);

        }catch (Exception e){
            e.printStackTrace();
            log.error("发生错误,错误信息为{}",e.getMessage());
        }


        return result;
    }


    public static Map<String,String> createHeader(String sId,String uId){
        HashMap<String, String> headers = new HashMap<>();
        if(sId!=null && sId!=""){
            headers.put("X-Sid",sId);
        }
        if(uId!=null && uId!=""){
            headers.put("X-Uid",uId);
        }
        headers.put("X-T",Long.toString(LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"))));
        headers.put("X-Pv","5.1");
        headers.put("X-Sign","ab21c4002078");
        headers.put("X-Appkey","21646297");
        return headers;
    }

    public static Map<String,String> createHeader(){
        return createHeader("","");
    }

    public static String createSign(String mH5Tk,String time,String appkey,String data){
        return DigestUtils.md5DigestAsHex(String.format("%s&%s&%s&%s", mH5Tk, time, appkey, data).getBytes());
    }

    public static void main(String[] args) {
        parseMl("￥sVfWYqHzkva￥");
    }
}
